<script setup>
import { inject, ref, provide, onMounted } from "vue";
import config from "@cwd/config/crud";
import { isFunction, get, isArray, isObject } from "lodash";
import CustomRender from "../js/custom-render";
import { ElMessage } from "element-plus";
import tool from "@/utils/tool";

const emit = defineEmits(["refresh"]);

const props = defineProps({
  columns: Array,
  isRecovery: Boolean,
  crudFormRef: Object,
});

//基础父级
const options = inject("options");
const requestParams = inject("requestParams");
const dictColors = inject("dictColors");
const dicts = inject("dicts");
const dictTrans = inject("dictTrans");

const getIndex = (rowIndex) => {
  const index = rowIndex + 1;
  if (requestParams[config.request.page] === 1) {
    return index;
  } else {
    return (
      (requestParams[config.request.page] - 1) *
        requestParams[config.request.pageSize] +
      index
    );
  }
};
//可编辑行操作
const allowQuickEdit = (formType) =>
  ["select", "input", "input-number", "radio"].includes(formType ?? "input");
//查看详情
const viewAction = (record) => {
  if (isFunction(options.beforeOpenSee) && !options.beforeOpenSee(record)) {
    return false;
  }
  if (options.see.action && isFunction(options.see.action)) {
    options.see.action(record);
  } else {
    props.crudFormRef.see(record);
  }
};
// 编辑详情
const editAction = (record) => {
  if (isFunction(options.beforeOpenEdit) && !options.beforeOpenEdit(record)) {
    return false;
  }
  if (options.edit.action && isFunction(options.edit.action)) {
    options.edit.action(record);
  } else {
    props.crudFormRef.edit(record);
  }
};
//回收站信息恢复
const recoveryAction = async (record) => {
  const response = await options.recovery.api({ ids: [record[options.pk]] });
  response.success && ElMessage.success(response.message || `恢复成功！`);
  emit("refresh");
};
//刷新
const refresh = () => {
  emit("refresh");
};

//数据删除
const deleteAction = async (record) => {
  let data = {};
  if (
    isFunction(options.beforeDelete) &&
    !(data = options.beforeDelete([record[options.pk]]))
  ) {
    return false;
  }
  const api = props.isRecovery ? options.delete.realApi : options.delete.api;
  const response = await api(
    Object.assign({ ids: [record[options.pk]] }, data)
  );
  if (options.afterDelete && isFunction(options.afterDelete)) {
    options.afterDelete(response, record);
  }
  response.code == 200 && ElMessage.success(response.message || `删除成功！`);
  emit("refresh");
};
//获取指定值
const getDataIndex = (row, record) => {
  if (isObject(record)) {
    return dictTrans(
      row.dataIndex,
      row.dataIndex.indexOf(".") > -1
        ? get(record, row.dataIndex)
        : record[row.dataIndex]
    );
  } else {
    return dictTrans(row.dataIndex, record);
  }
};
//获取tag 颜色
const getTagColor = (row, record) => {
  return dictColors(
    row.dataIndex,
    row.dataIndex.indexOf(".") > -1
      ? get(record, row.dataIndex)
      : record[row.dataIndex]
  );
};

defineExpose({ deleteAction, recoveryAction });
</script>
<template>
  <template v-for="item in columns" :key="item.dataIndex">
    <el-table-column
      :prop="item.dataIndex"
      :label="item.title"
      :align="item.textAlign ? item.textAlign : options.textAlign"
      v-if="!item.hide"
      :min-width="item.width ? item.width : options.columnWidth"
      :fixed="item.fixed"
    >
      <template #header>
        {{ item.title }}
      </template>
      <template #default="{ row, $index }">
        <slot :name="item.dataIndex" v-bind="{ record: row }">
          <template v-if="item.dataIndex === '__operation'">
            <!-- 默认的操作栏内容 -->
            <el-scrollbar>
              <div class="__crud-scrollbar-flex-content">
                <slot name="operationBeforeExtend" :record="row"></slot>
                <slot name="operationCell" v-bind="{ record: row }">
                  <!-- 查看详情 -->
                  <el-link
                    v-if="
                      (isFunction(options.see.show)
                        ? options.see.show(row)
                        : options.see.show) && !props.isRecovery
                    "
                    type="primary"
                    :status="options.see.status || 'success'"
                    :style="{ color: options.see.color || '' }"
                    :disabled="
                      isFunction(options.see.disabled)
                        ? options.see.disabled(row)
                        : options.see.disabled
                    "
                    @click="viewAction(row)"
                    class="__crud-operation-item"
                  >
                    <icon icon="ri-eye-line" ></icon>
                    <span class="tw-text-sm">{{
                        options.see.text || "查看"
                      }}</span>
                  </el-link>
                  <!-- 编辑 -->
                  <el-link
                    v-if="
                      (isFunction(options.edit.show)
                        ? options.edit.show(row)
                        : options.edit.show) && !props.isRecovery
                    "
                    type="primary"
                    :status="options.edit.status || 'success'"
                    :style="{ color: options.edit.color || '' }"
                    :disabled="
                      isFunction(options.edit.disabled)
                        ? options.edit.disabled(row)
                        : options.edit.disabled
                    "
                    @click="editAction(row)"
                    class="__crud-operation-item mx-1"
                  >
                    <icon icon="ri-edit-2-fill" ></icon
                    ><span class="text-sm">
                      {{ options.edit.text || "编辑" }}</span
                    >
                  </el-link>
                  <!-- 数据恢复 -->
                  <el-popconfirm
                    title="确定要恢复该数据吗?"
                    @confirm="recoveryAction(row)"
                    v-if="
                      (isFunction(options.recovery.show)
                        ? options.recovery.show(row)
                        : options.recovery.show) && props.isRecovery
                    "
                    class="__crud-operation-item"
                  >
                    <template #reference>
                      <el-link
                        type="primary"
                        v-if="
                          (isFunction(options.recovery.show)
                            ? options.recovery.show(row)
                            : options.recovery.show) && props.isRecovery
                        "
                        class="__crud-operation-item mx-1"
                      >
                        <icon icon="ri-reply-fill"> </icon>
                        <span class="text-sm">{{
                          options.recovery.text || "恢复"
                        }}</span>
                      </el-link>
                    </template>
                  </el-popconfirm>
                  <!-- 删除数据 -->
                  <el-popconfirm
                    width="190"
                    title="确定要删除该数据吗?"
                    @confirm="deleteAction(row)"
                    v-if="
                      isFunction(options.delete.show)
                        ? options.delete.show(row)
                        : options.delete.show
                    "
                    class="__crud-operation-item"
                  >
                    <template #reference>
                      <el-link
                        type="primary"
                        :status="options.delete.status || 'danger'"
                        :style="{ color: options.delete.color || '' }"
                        :disabled="
                          isFunction(options.delete.disabled)
                            ? options.delete.disabled(row)
                            : options.delete.disabled
                        "
                      >
                        <icon icon="ri-delete-bin-5-fill" > </icon>
                        <span class="text-sm">
                          {{
                            props.isRecovery
                              ? options.delete.realText || "删除"
                              : options.delete.text || "删除"
                          }}
                        </span>
                      </el-link>
                    </template>
                  </el-popconfirm>
                </slot>
                <slot name="operationAfterExtend" :record="row"></slot>
              </div>
            </el-scrollbar>
          </template>
          <template v-else-if="item.customRender">
            <custom-render :record="row"></custom-render>
          </template>
          <template v-else>
            <template v-if="item.dataIndex === '__index'">{{
              getIndex($index)
            }}</template>
            <span
              :class="[
                'relative',
                item?.quickEdit && allowQuickEdit(item.formType) ? 'flex' : '',
              ]"
            >
              <template v-if="item.isEdit">
                <!-- 可编辑的内容 -->
              </template>
              <template v-else-if="item?.dict && item?.dict?.translation">
                <template v-if="isArray(get(row, item.dataIndex))">
                  <el-tag
                    v-for="(tagItem, index) in get(row, item.dataIndex)"
                    :key="index"
                    class="ml-1"
                    type="primary"
                    >{{ getDataIndex(item, tagItem) }}</el-tag
                  >
                </template>
                <el-tag v-else-if="item.dict.tagColors">
                  {{ getDataIndex(item, row) }}
                </el-tag>
                <el-tag v-else-if="item.dict.tagColor" type="primary">{{
                  getDataIndex(item, row)
                }}</el-tag>
                <span v-else>{{ getDataIndex(item, row) }}</span>
              </template>
              <template
                v-else-if="item.dataIndex && item.dataIndex.indexOf('.') !== -1"
              >
                <!-- 嵌套属性的内容 -->
              </template>
              <template v-else-if="item.formType === 'avatar'">
                <el-avatar
                  :size="40"
                  :src="tool.attachUrl(row[item.dataIndex])"
                />
                <!-- <el-avatar :size="40" :src="row[item.dataIndex]" /> -->
              </template>
              <template v-else>{{ row[item.dataIndex] }}</template>
              <el-link
                class="tw-absolute tw-top-1 tw-right-0"
                v-if="
                  item?.quickEdit &&
                  allowQuickEdit(item.formType) &&
                  !item.isEdit
                "
                @click="quickEdit(item, row)"
              ></el-link>
            </span>
          </template>
        </slot>
      </template>
    </el-table-column>
  </template>
</template>
<style lang="less">
.__crud-scrollbar-flex-content {
  display: inline-flex;

  .__crud-operation-item {
    margin-right: 4px;
  }
}
</style>